'''
FUba PLC通讯 业务逻辑

'''
import threading
import time
import traceback

# sys.path.append(r'D:\code\huoNiWeiEr\project_huoni_v2\neith_fyluoding\plc_S7')
# from plc_S7.s7_client import lay1_client
# 导入layer1_client
try:
    from plc_client.layer1.factory import Lay1PLCFactory
except:
    from ..layer1.factory import Lay1PLCFactory

# 导入ABCProjectPlcClient
try:
    from plc_client.layer2.ABCProjectPlcClient import ProjectPlcClient
except:
    from ..layer2.ABCProjectPlcClient import ProjectPlcClient

try:
    from log import logger
except:
    from ...log import logger




class FubaPlcClient(ProjectPlcClient): # 一个点位一个plc客户端 （各点位plc逻辑类似）
    def __init__(self, lay1_client_name = 'modbus_tcp' ):
        super().__init__()
        config = {
            'ip': '192.168.0.1',
            'port': 102,
            'dbnumber': 183,
            'name_addr_dict': {
                'p1.is_jc':0,
                'p1.jc_res':1,
                'p2.is_jc':2,
                'p2.jc_res':10,
                'is_ready':0
            }
            
        }
        self.config = config
        self.lay1_client = Lay1PLCFactory.create(lay1_client_name, config['ip'], config['port']) # 可根据lay1_client_name选择对象
        # self.lay1_client = lay1_client_class(config['ip'], config['port'])
        self.lock = threading.Lock() # 同步

    def connect(self):
        self.lay1_client.connect()

    def close(self):
        self.lay1_client.close()

    def isConnected(self):
        return self.lay1_client.get_connected()

    def wait_plc(self, get_trigger_signal, set_zero_trigger_signal, var_name='p1.is_jc',
                 is_continue_fun_1=None):  # self.get_is_scan_done, set_zero_is_scan_done
        '''
        usage:
        self.wait(self.get_is_scan_done, self.set_zero_is_scan_done)
        :param get_chufa_fun1:
        :param set_zeros_fun2:
        :return:
        '''
        isDone = 0  # 1 ture 2 false
        while isDone == 0:
            isDone = get_trigger_signal(var_name)  #
            if is_continue_fun_1 is not None and not is_continue_fun_1():  # break when is_continue_fun_1 is false
                break
            time.sleep(0.1)  # s
        set_zero_trigger_signal(var_name)  # to 0
        print(f"{var_name} isDone {isDone}")

    def set_is_ready(self, is_ready):
        self.lock.acquire()
        self.lay1_client.write_int8(start=self.config['name_addr_dict']['is_ready'], data_int8=is_ready)
        self.lock.release()

    def get_trigger_signal(self, var_name='p1.is_jc'):  # 是否引导
        try:
            self.lock.acquire()
            is_yd = self.lay1_client.read_int8(start=self.config['name_addr_dict'][var_name])
            self.lock.release()
        except Exception as e:
            logger.error(e)
            logger.error(traceback.format_exc())
            self.lock.acquire()
            self.close()
            logger.info('re connecting')
            self.connect() # 重连
            self.lock.release()
            return 0

        return is_yd

    def set_zero_trigger_signal(self, var_name='p1.is_jc'):  # 是否引导 置0
        self.lock.acquire()
        self.lay1_client.write_int8(start=self.config['name_addr_dict'][var_name], data_int8=0)
        self.lock.release()
        return


    def set_res(self, yd_res, var_name='p1.jc_res'):  # 引导结果
        self.lock.acquire()
        try:
            pass
        except Exception as e:
            print('发送引导结果失败')
            print(e)
        self.lock.release()





def test_FubaPlcClient():

    hn_plc = FubaPlcClient()
    hn_plc.connect()
    hn_plc.set_is_ready(1)
    hn_plc.close()


if __name__ == "__main__":
    # test_HuoniPlcClinet()
    test_FubaPlcClient()
